package com.yeeft.ocr.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.net.InetAddress;

/**
 *  生成SHA-1 = sha1(appId + supplierId + imageUrl + currentTime)
 *
 * @author 赵仲文
 * @Copyright (c) 2016, frontpay.cn
 * @date 2018/5/11 10:38
 */

@Slf4j
public class Sha1KeyGenerator {
        private static final String IP;

        static {
            String hostName;
            try {
                hostName = InetAddress.getLocalHost().getHostName();
                log.info("Sha1KeyGenerator retrieved IP address: ", hostName);
            } catch (Exception e) {
                hostName = "";
                log.error(e.getMessage(), e);
            }

            IP = hostName;
        }

        public static int toInt(byte[] bytes) {
            int result = 0;
            for (int i = 0; i < 4; i++) {
                result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
            }
            return result;
        }

        static public String get(String appId, Integer supplierId, String imageUrl) {
            int seedInit = RandomUtils.nextInt(1, 2000000);
            long threadId = Thread.currentThread().getId();
            int seedStart = RandomUtils.nextInt(3000001, 5000000);
            String currentTime = DateUtils.getCurrentDate().toString();
            int seedEnd = RandomUtils.nextInt(7000001, 9000000);
            return Digests.byteToString(Digests.sha1(new StringBuffer().append(seedInit).append(threadId).append(seedStart).
                    append(appId).append(supplierId).append(imageUrl).append(currentTime).append(seedEnd).append(IP).toString().getBytes()));
        }

        static public String get() {
            int seedInit = RandomUtils.nextInt(1, 2000000);
            long threadId = Thread.currentThread().getId();
            int seedStart = RandomUtils.nextInt(3000001, 5000000);
            String currentTime = DateUtils.getCurrentDate().toString();
            int seedEnd = RandomUtils.nextInt(7000001, 9000000);
            return Digests.byteToString(Digests.sha1(new StringBuffer().append(seedInit).append(threadId).append(currentTime).
                    append(seedStart).append(seedEnd).append(IP).toString().getBytes()));
        }
}
